package org.example.interceptor;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.example.enums.BizCodeEnum;
import org.example.model.LoginUser;
import org.example.util.CommonUtil;
import org.example.util.JsonData;
import org.example.util.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<LoginUser> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、从请求头中获取token
        String accessToken = request.getHeader("token");
        //2、如果请求头中没有，就去url里获取
        if (accessToken == null) {
            accessToken = request.getParameter("token");
        }
        //3、如果获取到了token，就解析
        if (accessToken != null) {
            Claims claims = JwtUtil.checkJwt(accessToken);
            //4、如果claims为空，说明token无效
            if (claims == null) {
                //返回json给前端看
                CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
                return false;
            }
            //5、如果claims不为空，就获取值并封装
            Long userId = Long.valueOf(claims.get("id").toString());
            String name = (String) claims.get("name");
            String headImg = (String) claims.get("head_img");
            String mail = (String) claims.get("mail");
            LoginUser loginUser = LoginUser.builder()
                    .id(userId)
                    .name(name)
                    .headImg(headImg)
                    .mail(mail).build();
            threadLocal.set(loginUser);
            return true;
        }
        CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        threadLocal.remove();
    }
}
